package com.gui.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.gui.hosp.repository.ScheduleRepository;
import com.gui.hosp.service.DepartmentService;
import com.gui.hosp.service.HospitalService;
import com.gui.hosp.service.ScheduleService;
import com.gui.model.hosp.Schedule;
import com.gui.vo.hosp.BookingScheduleRuleVo;
import com.gui.vo.hosp.ScheduleQueryVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author GodLamp
 * @date 2022/10/21 20:28
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Resource
    private ScheduleRepository scheduleRepository;

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private HospitalService hospitalService;

    @Resource
    private DepartmentService departmentService;

    /**
     * 上传科室信息
     *
     * @param params
     */
    @Override
    public void save(Map<String, Object> params) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(params), Schedule.class);

        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        if (scheduleExist != null) {
            //修改
            scheduleExist.setIsDeleted(0);
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        } else {
            //添加
            schedule.setIsDeleted(0);
            schedule.setUpdateTime(new Date());
            schedule.setStatus(1);
            schedule.setCreateTime(new Date());
            scheduleRepository.save(schedule);
        }
    }

    /**
     * 查询排班信息
     *
     * @param page
     * @param limit
     * @param vo
     * @return
     */
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo vo) {
        Pageable pageable = PageRequest.of(page, limit);

        //转换对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(vo, schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        Example<Schedule> example = Example.of(schedule, exampleMatcher);

        return scheduleRepository.findAll(example, pageable);
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);

        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * 根据医院编号、科室编号查询排班规则信息
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleSchedule(Integer page, Integer limit, String hoscode, String depcode) {
        //1.根据医院编号、科室编号查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2.根据工作日期workDate进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria), //匹配条件
                Aggregation.group("workDate") //分组字段
                        .first("workDate").as("workDate") //别名
                        .count().as("docCount") //3.统计号源数量
                        .sum("reservedNumber").as("reservedNumber") //统计科室可预约数
                        .sum("availableNumber").as("availableNumber"), //统计科室剩余预约数
                Aggregation.sort(Sort.Direction.DESC, "workDate"), //排序
                //4.实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );

        //执行查询,获取数据
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVos = aggregate.getMappedResults();

        //分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalRuleVos = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);
        int total = totalRuleVos.getMappedResults().size();

        //获取日期对应星期
        for (BookingScheduleRuleVo ruleVo : bookingScheduleRuleVos) {
            Date workDate = ruleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            ruleVo.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据,并返回
        Map<String, Object> map = new HashMap<>();

        map.put("bookingScheduleRuleList", bookingScheduleRuleVos);
        map.put("total", total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //存放其他基础信息
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hosName);

        map.put("baseMap", baseMap);

        return map;
    }

    /**
     * 根据医院编号、科室编号、工作日期查询排班详细信息
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //根据参数查询MongoDB
        List<Schedule> list = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());

        //遍历list集合，设置其他信息，比如医院名称、科室名称、日期对应星期
        list.stream().forEach(it -> {
            this.packageSchedule(it);
        });

        return list;
    }

    /**
     * 设置其他信息，比如医院名称、科室名称、日期对应星期
     * @param it
     */
    private void packageSchedule(Schedule it) {
        it.getParam().put("hosname", hospitalService.getHospName(it.getHoscode()));
        it.getParam().put("depname", departmentService.getDepName(it.getHoscode(), it.getDepcode()));
        it.getParam().put("dayOfWeek", getDayOfWeek(new DateTime(it.getWorkDate())));
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }

}
